package com.kgc.scd.controller;

import com.alibaba.fastjson.JSON;
import com.kgc.scd.annotation.RequestShopUser;
import com.kgc.scd.annotation.TokenPermission;
import com.kgc.scd.bean.ShopUser;
import com.kgc.scd.constant.CommonConstant;
import com.kgc.scd.service.ShopCartFeignService;
import com.kgc.scd.util.PageSupport;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import com.kgc.scd.vo.ShopCartVO;
import com.kgc.scd.vo.ShopGoodsVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created On : 2022/11/16 0016.
 * <p>
 * Author : shiguangchuan
 * <p>
 * Description: ShopCarController
 */
@Slf4j
@RestController
@RequestMapping("/sgc")
@Api(tags = "购物车相关操作接口",value = "用户可在商品详情页面以及首页商品的界面，将需要购买的信息添加购物车，需要判断用户是否登录")
@TokenPermission
public class ShopCarController {

    @Autowired
    private ShopCartFeignService shopCartFeignService;

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : [goodsId, cartNumber, shopUser]
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 通过调用远程购物车接口，达到将商品信息添加到购物车中
     */
    @PostMapping("/insertShopCart")
    @ApiOperation(value = "添加商品到购物车中",notes = "用户将选择商品的数量然后添加到购物车中")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品编号id",required = true),
            @ApiImplicitParam(name = "cartNumber",value = "添加的数量",required = true)
    })
    public RequestResult<?> insertShopCart(@RequestParam String goodsId,
                                           @RequestParam Integer cartNumber,
                                           @ApiIgnore @RequestShopUser ShopUser shopUser){

        if (cartNumber == null || goodsId == null){
            return ResultBuildUtil.fail("传入参数不能为空！");
        }

        if (cartNumber < 1){
            return ResultBuildUtil.fail("数量不能小于1！");
        }

        if (cartNumber > 50){
            return ResultBuildUtil.fail("超出商品的最大购买量50，请重新修改需要购买的商品数量！");
        }

        // 判断当前用户的购物车内的商品数量是否已经达到上限
        if(shopCartFeignService.feignInvokeSelectCartCount(shopUser.getId()) == 5 ){

            return ResultBuildUtil.fail("购物车内的商品数量已经达到最大限制量5，请先删除一部分商品再添加");

        }

        // 调用远程购物车请求方法，执行添加到购物车的业务
        if (shopCartFeignService.feignInvokeInsertShopCart(shopUser.getId(),goodsId,cartNumber)){
            return ResultBuildUtil.success("添加成功！");
        }

        return ResultBuildUtil.fail("商品库存不足，添加失败！");

    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : [goodsId, cartNumber, shopUser]
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 修改购物车中单品的数量
     */
    @PostMapping("/updateShopCart")
    @ApiOperation(value = "修改购物车中单品的数量",notes = "用户可以修改购物车中商品的数量，但是也存在上限和下限")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",value = "商品编号id",required = true),
            @ApiImplicitParam(name = "cartNumber",value = "修改的数量",required = true)
    })
    public RequestResult<?> updateShopCart(@RequestParam String goodsId,
                                           @RequestParam Integer cartNumber,
                                           @ApiIgnore @RequestShopUser ShopUser shopUser){

        if (goodsId == null || cartNumber == null){
            return ResultBuildUtil.fail("传入参数不能为空！");
        }

        if (cartNumber < 1){
            return ResultBuildUtil.fail("数量不能小于1！");
        }

        if (cartNumber > 50){
            return ResultBuildUtil.fail("超出商品的最大购买量50，请重新修改需要购买的商品数量！");
        }

        // 调用远程购物车请求方法，执行添加到购物车的业务
        if (shopCartFeignService.feignInvokeUpdateShopCart(shopUser.getId(),goodsId,cartNumber)){
            return ResultBuildUtil.success("修改数量成功！");
        }

        return ResultBuildUtil.fail("修改数量失败！");

    }


    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : [ids]
     * @return : com.kgc.scd.util.RequestResult<java.lang.String>
     * @description : 删除单个或多个购物车的商品
     */
    @PostMapping("/deleteShopCart")
    @ApiOperation(value = "单个或批量删除购物车商品",notes = "用户通过id删除单个或多个购物车信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "购物车id列表",required = true,allowMultiple = true)
    })
    public RequestResult<String> deleteShopCartByIds(@RequestParam List<String> ids){

        // 判断是否有参数传入
        if(ids.size() == 0){

            return ResultBuildUtil.fail("需要删除的购物车id不能为空！");

        }

        // 调用远程删除购物车的接口
        if(shopCartFeignService.feignInvokeDeleteCartByIds(ids)){
            return ResultBuildUtil.success("删除成功！");
        }

        return ResultBuildUtil.fail("删除失败！");

    }


    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : [shopUser]
     * @return : com.kgc.scd.util.RequestResult<java.lang.String>
     * @description : 清空购物车
     */
    @PostMapping("/deleteAllShopCart")
    @ApiOperation(value = "清空购物车",notes = "通过用户信息，清除全部的购物车信息")
    public RequestResult<String> deleteShopAllCartByUserId(@ApiIgnore @RequestShopUser ShopUser shopUser){

        // 调用远程删除购物车的接口
        if(shopCartFeignService.feignInvokeDeleteAllCart(shopUser.getId())){
            return ResultBuildUtil.success("清空购物车成功！");
        }

        return ResultBuildUtil.fail("你还没有添加过任何商品，请先去添加哦！");

    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : []
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 用户对一个商品的选取状态
     */
    @PostMapping("/updateShopCartStatus")
    @ApiOperation(value = "用户对购物车商品的勾选操作(单选操作)",notes = "用户对购物车的商品点击操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "购物车id")
    })
    public RequestResult<?> updateShopCartStatus(@RequestParam String id){

        // 调用远程方法，实现对单个商品的选择
        shopCartFeignService.feignInvokeUpdateCartOneStatus(id);

        return ResultBuildUtil.success("勾选操作成功！");

    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/16 0016
     * @param  : [shopUser, allStatus]
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 执行全选的对应操作 
     */
    @PostMapping("/updateAllShopCartStatus")
    @ApiOperation(value = "用户对购物车商品的勾选操作(全选操作)",notes = "用户对购物车的商品点击操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "allStatus",value = "全选状态传入：0代表取消全选，1代表全选")
    })
    public RequestResult<?> updateAllShopCartStatus(@ApiIgnore @RequestShopUser ShopUser shopUser,
                                                 @RequestParam Integer allStatus){


        if(allStatus != 0 && allStatus != 1){

            return ResultBuildUtil.fail("传入状态值不符合要求，请重新填写发送！");

        }

        // 调用远程方法，实现对全部商品的操作
        shopCartFeignService.feignInvokeUpdateAllCartStatus(shopUser.getId(),allStatus);
        
        if (allStatus == 0){
            return ResultBuildUtil.success("取消全选成功！");
        }

        return ResultBuildUtil.success("全选成功！");

    }


    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0017
     * @param  : [shopUser]
     * @return : com.kgc.scd.util.RequestResult<?>
     * @description : 根据商品的选中状态计算总价格 
     */
    @PostMapping("/selectSumShopCart")
    @ApiOperation(value = "获取该用户购物车已经选中的所有商品总价格",notes = "根据商品的选中状态")
    public RequestResult<?> selectSumShopCart(@ApiIgnore @RequestShopUser ShopUser shopUser){

        // 调用远程方法，实现对全部商品的操作
        Double sumPrice = shopCartFeignService.feignInvokeSelectSumCart(shopUser.getId());

        return ResultBuildUtil.success(sumPrice);

    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0017
     * @param  : [pageNo, pageSize, shopUser]
     * @return : com.kgc.scd.util.RequestResult<com.kgc.scd.util.PageSupport<java.util.Map<com.kgc.scd.vo.ShopCartVO,com.kgc.scd.vo.ShopGoodsVO>>>
     * @description : 购物车页面
     */
    @GetMapping("/getShopCartList")
    @ApiOperation(value = "购物车页面",notes = "通过用户，将用户的的购物车全部展示出来，带分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo",value = "页码"),
            @ApiImplicitParam(name = "pageSize",value = "页面条数")
    })
    public RequestResult<PageSupport<List<ShopCartVO>>> selectHistoryList(@RequestParam(defaultValue = CommonConstant.DEFAULT_INIT_PAGE_NO) Integer pageNo,
                                                                           @RequestParam(defaultValue = CommonConstant.DEFAULT_INIT_PAGE_SIZE) Integer pageSize,
                                                                           @ApiIgnore @RequestShopUser ShopUser shopUser){

        // 调用远程业务接口，显示购物车页面，判断该用户购物车内是否为空
        if (shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId()).getPageData() != null && !shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId()).getPageData().isEmpty()) {

            // 购物车中存在信息
            return ResultBuildUtil.success(shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId()));
        }

        // 用户购物车商品为空的情况
        return ResultBuildUtil.fail("300","当前还没有添加任何商品到购物车，请去添加。");

    }

    /**
     * @author : shiguangchuan
     * @date   : 2022/11/17 0017
     * @param  : [pageNo, pageSize, shopUser]
     * @return : com.kgc.scd.util.RequestResult<com.kgc.scd.util.PageSupport<java.util.Map<com.kgc.scd.vo.ShopCartVO,com.kgc.scd.vo.ShopGoodsVO>>>
     * @description : 购物车页面 
     */
    /*@GetMapping("/getShopCartList")
    @ApiOperation(value = "购物车页面",notes = "通过用户，将用户的的购物车全部展示出来，带分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo",value = "页码"),
            @ApiImplicitParam(name = "pageSize",value = "页面条数")
    })
    public RequestResult<Map<ShopCartVO,ShopGoodsVO>> selectHistoryList(@RequestParam(defaultValue = CommonConstant.DEFAULT_INIT_PAGE_NO) Integer pageNo,
                                                                         @RequestParam(defaultValue = CommonConstant.DEFAULT_INIT_PAGE_SIZE) Integer pageSize,
                                                                         @ApiIgnore @RequestShopUser ShopUser shopUser){
        
        // 调用远程业务接口，显示购物车页面，判断该用户购物车内是否为空
        if (shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId()) != null && !shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId()).isEmpty()) {

            // 调用业务接口，将购物车信息存入map，方便后面的实体映射
            Map<String,ShopGoodsVO> map = shopCartFeignService.feignInvokeSelectCartList(pageNo,pageSize,shopUser.getId());

            // 创建map
            Map<ShopCartVO,ShopGoodsVO> newMap = new HashMap<>();

            // 使用迭代器
            for (String key : map.keySet()) {
                // 将获取到的key映射到购物车详情实体中
                ShopCartVO shopCartVO = JSON.parseObject(key, ShopCartVO.class);

                // 通过map中的key取到购物车实体对应的商品实体信息
                ShopGoodsVO shopGoodsVO = map.get(key);

                // 将实体存入map，方便放回前端
                newMap.put(shopCartVO, shopGoodsVO);
            }

            // 购物车中存在信息
            return ResultBuildUtil.success(newMap);
        }

        // 用户购物车商品为空的情况
        return ResultBuildUtil.fail("300","当前还没有添加任何商品到购物车，请去添加。");
        
    }*/

}
